package la.bbs558.aop.delay;

import com.alibaba.fastjson.JSON;
import la.bbs558.util.ApplicationUtils;
import la.bbs558.util.Objs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @Classname DelayAspect
 * @Description TODO
 * @Date 2023/11/11 17:12
 * @Created by weihanmin
 */
@Aspect
@Component
@Slf4j
public class DelayAspect {

    @SneakyThrows
    @Around("@annotation(delay)")
    public Object run(ProceedingJoinPoint jp, Delay delay) {
        //获取类的字节码对象，通过字节码对象获取方法信息
        // Class<?> targetCls = jp.getTarget().getClass();
        //获取方法签名(通过此签名获取目标方法信息)
        // MethodSignature ms = (MethodSignature) jp.getSignature();
        //获取目标方法上的注解指定的操作名称
        // Method targetMethod = targetCls.getDeclaredMethod(ms.getName(), ms.getParameterTypes());
        Serializable proceed = (Serializable) jp.proceed();
        DelayQueueEnum delayQueueEnum = delay.queueId();
        long timeout = delay.timeout();
        TimeUnit timeunit = delay.timeunit();
        int maxRetry = delay.maxRetry();
        Class<? extends DelayHandler> delayHandlerClass = delay.delayHandler();
        if (delayHandlerClass.equals(DefaultDelayHandler.class)) {
            delayHandlerClass = delayQueueEnum.getHandlerClass();
        }
        DelayHandler delayHandler = ApplicationUtils.getBean(delayHandlerClass);
        Objs.valid(delayHandler,"缺少延时任务处理器");
        DelayQueueManager delayQueue = DelayQueueManager.getDelayQueue(delayQueueEnum);
        boolean addTask = delayQueue.addTask(new DelayTask<>(proceed, timeout, timeunit, maxRetry, delayHandler));
        if (addTask) {
            log.info("延时任务创建成功,task={}", JSON.toJSONString(proceed));
        } else {
            log.warn("延时任务创建失败,task={}", JSON.toJSONString(proceed));
        }
        return proceed;
    }
}
